﻿/***************************************************
//  Copyright (c) Premium Tax Free 2011
/***************************************************/

using System;
using System.Drawing;
using System.Windows.Forms;
using PremierTaxFree.PTFLib.Extensions;

namespace PremierTaxFree.Tools
{
    public class EraserTool : BaseTool
    {
        private Point m_CurrentPoint = Point.Empty;
        private bool m_Started = false;
        private Bitmap m_Erazer;

        public EraserTool(CanvasControl canvas)
            : base(canvas)
        {
            m_Erazer = new Bitmap(m_Canvas.EraserSize.Width, m_Canvas.EraserSize.Height);
            using (Graphics g = Graphics.FromImage(m_Erazer))
                g.Clear(m_Canvas.BackColor);
        }

        ~EraserTool()
        {
            m_Erazer.Dispose();
        }

        protected override void MouseDown(object sender, MouseEventArgs e)
        {
            m_Started = (e.Button == MouseButtons.Left);
        }

        protected override void MouseUp(object sender, MouseEventArgs e)
        {
            if (m_Started)
            {
                SaveTool();
                m_Started = false;
            }
        }

        protected override void MouseLeave(object sender, EventArgs e)
        {
            if (m_Started)
            {
                SaveTool();
                m_Started = false;
            }
        }

        protected override void Click(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle(m_CurrentPoint, m_Canvas.EraserSize);
            using (Graphics g = Graphics.FromHwnd(m_Canvas.Handle)) 
                g.FillRectangle(Brushes.White, m_Canvas.RectangleToClient(rect));

            SaveTool();
            m_Started = false;
        }

        protected override void MouseMove(object sender, MouseEventArgs e)
        {
            Rectangle rect = new Rectangle(m_CurrentPoint, m_Canvas.EraserSize);
            ControlPaint.FillReversibleRectangle(rect, Color.Black);
            m_CurrentPoint = Control.MousePosition;
            ControlPaint.FillReversibleRectangle(rect, Color.Black);

            if (m_Started)
            {
                using (Graphics g = Graphics.FromHwnd(m_Canvas.Handle))
                    ControlPaint.DrawImageDisabled(g, m_Erazer, e.Location.X, e.Location.Y, Color.White);
                SaveTool();
            }
        }

        protected override void SaveTool()
        {
            Bitmap desktop = ImageHelper.GetDesktopImage();
            Bitmap bmp = desktop.Crop(m_Canvas.RectangleToScreen(m_Canvas.ClientRectangle));

            Image img = m_Canvas.BackgroundImage;
            ImageHelper.UpdateSafe(ref img, bmp);
            m_Canvas.BackgroundImage = img;
        }
    }
}
